package com.example.tzsdownload;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.*;
import java.util.HashMap;
import java.util.Map;


@SpringBootApplication
public class TzsdownloadApplication {

    public static void main(String[] args) {
        SpringApplication.run(TzsdownloadApplication.class, args);
        test();


        //createPDF("",data);


    }


    public static boolean createPDF(String outFilePath, Map<String, Object> data) {

        //模板路径
        String templatePath = "D:\\ccc\\11111111.pdf";
        //生成的新文件路径
        String newPDFPath = outFilePath;
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            out = new FileOutputStream(newPDFPath);//输出流
            reader = new PdfReader(templatePath);//读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            /**
             * 使用中文字体 使用 AcroFields填充值的不需要在程序中设置字体，在模板文件中设置字体为中文字体 Adobe 宋体 std L
             */
            BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
            /**
             * 设置编码格式
             */
            form.addSubstitutionFont(bfChinese);

            // 遍历data 给pdf表单表格赋值
//            for (String key : data.keySet()) {
//                //s.setField(key, data.get(key).toString());
//                form.setField(key, data.get(key).toString());
//            }


            form.setField("mz",data.get("mz").toString());
            form.setField("xy",data.get("xy").toString());
            form.setField("cc",data.get("cc").toString());
            form.setField("zy",data.get("zy").toString());
            form.setField("tzsbh",data.get("tzsbh").toString());
            form.setField("ksh",data.get("ksh").toString());



            stamper.setFormFlattening(true);//如果为false那么生成的PDF文件还能编辑，一定要设为true
            //stamper.setFreeTextFlattening(true);
            stamper.close();

            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(
                    new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
           e.printStackTrace();
        }

        return false;
    }


    public static void test(){

        String excelPath = "d:\\ccc\\11111111.xlsx";

        try {
            //String encoding = "GBK";
            File excel = new File(excelPath);
            if (excel.isFile() && excel.exists()) {   //判断文件是否存在

                String[] split = excel.getName().split("\\.");  //.是特殊字符，需要转义！！！！！
                Workbook wb;
                //根据文件后缀（xls/xlsx）进行判断
                if ( "xls".equals(split[1])){
                    FileInputStream fis = new FileInputStream(excel);   //文件流对象
                    wb = new HSSFWorkbook(fis);
                }else if ("xlsx".equals(split[1])){
                    wb = new XSSFWorkbook(excel);
                }else {
                    System.out.println("文件类型错误!");
                    return;
                }

                //开始解析
                Sheet sheet = wb.getSheetAt(0);     //读取sheet 0

                int firstRowIndex = sheet.getFirstRowNum()+1;   //第一行是列名，所以不读
                int lastRowIndex = sheet.getLastRowNum();
                System.out.println("firstRowIndex: "+firstRowIndex);
                System.out.println("lastRowIndex: "+lastRowIndex);

                for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
                    //System.out.println("rIndex: " + rIndex);
                    Row row = sheet.getRow(rIndex);
                    if (row != null) {
                        int firstCellIndex = row.getFirstCellNum();
                        int lastCellIndex = row.getLastCellNum();


//                        for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {   //遍历列
//                            Cell cell = row.getCell(cIndex);
//                            System.out.print(cIndex + " ");
//                            if (cell != null) {
//                                System.out.print(cell.toString() + " ");
//                            }
//                        }
//
//                        System.out.println("");

                        Cell tzsnum = row.getCell(0);
                        Cell ksh = row.getCell(1);
                        Cell sfz = row.getCell(2);
                        Cell name = row.getCell(3);
                        Cell kl = row.getCell(4);
                        Cell pc = row.getCell(5);
                        Cell cc = row.getCell(6);
                        Cell zy = row.getCell(7);
                        Cell xy = row.getCell(8);

                        if (null == tzsnum){
                            continue;
                        }else {
                            System.out.print(name.toString()+" ");
                            System.out.print(xy.toString()+" ");
                            System.out.print(cc.toString()+" ");
                            System.out.print(zy.toString()+" ");
                            System.out.print(tzsnum.toString()+" ");
                            System.out.print(ksh.toString()+" ");
                            System.out.print(sfz.toString()+" ");

                            Map<String, Object> data = new HashMap<String, Object>();
                            data.put("mz", name.toString());
                            data.put("xy", xy.toString());
                            data.put("cc", cc.toString());
                            data.put("zy", zy.toString());
                            data.put("tzsbh", tzsnum.toString());
                            data.put("ksh", ksh.toString());

                            createPDF("D:\\ccc\\1\\"+sfz.toString()+"_"+ksh.toString()+".pdf",data);

                            Thread.sleep(1000);

                        }
                        System.out.println( " ");



                    }
                }
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
